package com.atguigu.gmall.payment.intercepter;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.payment.config.JwtProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginIntercepter implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;

    private static  final  ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal();
    /**
     * 对所有的请求进行身份确认，提出userinfo中的userId，userkey
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo userInfo = new UserInfo();
        //获取请求中的token
        String tokenJson = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());
        String userKey = CookieUtils.getCookieValue(request, jwtProperties.getUserKey());
        //为首次访问的用户设置userkey
        if (StringUtils.isBlank(userKey)){
            userKey= UUID.randomUUID().toString();//15552000
            CookieUtils.setCookie(request,response,jwtProperties.getUserKey(),userKey,jwtProperties.getExpireTime());
        }
            userInfo.setUserKey(userKey);
        //解析请求中的token
        if (StringUtils.isBlank(tokenJson)){
            userInfo.setUserId(null);
            THREAD_LOCAL.set(userInfo);//设置userInfo，不拦截
            return true;
        }
        //反之则token中有数据
        Map<String, Object> infoFromToken = JwtUtils.getInfoFromToken(tokenJson, jwtProperties.getPublicKey());
        String userId = infoFromToken.get("id").toString();
        userInfo.setUserId(Long.parseLong(userId));
        THREAD_LOCAL.set(userInfo);//设置userInfo，不拦截
        return true;
    }

    public static UserInfo getUserInfo(){
       return THREAD_LOCAL.get();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //手动释放，避免内存泄露
        THREAD_LOCAL.remove();
    }
}
